/**
 * Copyright 2020 OPSLI 快速开发平台 https://www.opsli.com
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.opsli.modulars.tenant.customerstatus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.opsli.api.wrapper.tenant.customerstatus.TenantStatusRuleModel;
import org.opsli.core.base.service.impl.CrudServiceImpl;
import org.opsli.modulars.tenant.customerstatus.entity.TenantStatusRule;
import org.opsli.modulars.tenant.customerstatus.mapper.TenantStatusRuleMapper;
import org.opsli.modulars.tenant.customerstatus.service.ITenantStatusRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 租户客户状态流转规则 Service Impl
 *
 * @author guagua
 * @date 2025-01-04
 */
@Slf4j
@Service
public class TenantStatusRuleServiceImpl
        extends CrudServiceImpl<TenantStatusRuleMapper, TenantStatusRule, TenantStatusRuleModel>
        implements ITenantStatusRuleService {

    @Autowired(required = false)
    private TenantStatusRuleMapper mapper;

    @Override
    public List<TenantStatusRuleModel> findByEventAndFromStatus(String eventCode, String fromStatus) {
        QueryWrapper<TenantStatusRule> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("event_code", eventCode)
                .eq("from_status", fromStatus)
                .eq("is_active", 1)
                .eq("deleted", 0)
                .orderByAsc("sort_order");

        List<TenantStatusRule> entityList = mapper.selectList(queryWrapper);
        return super.transformTs2Ms(entityList);
    }

    @Override
    public boolean executeStatusRule(String eventCode, String customerId, String params) {
        try {
            log.info("执行状态流转规则: eventCode={}, customerId={}, params={}", eventCode, customerId, params);

            // TODO: 具体的状态流转逻辑
            // 1. 获取客户当前状态
            // 2. 根据事件代码和当前状态查找匹配的规则
            // 3. 检查流转条件
            // 4. 执行状态变更
            // 5. 记录状态变更日志

            return true;
        } catch (Exception e) {
            log.error("执行状态流转规则失败: eventCode={}, customerId={}", eventCode, customerId, e);
            return false;
        }
    }
}